import {
  deleteCellConsistApi,
  checkItemBundleApi,
  callConsistApi,
  templateIdList,
} from "./api";
import Taro from "@tarojs/taro";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { watch } from "vue";

export const useButton = (state, userType) => {
  const {
    redirectTo,
    navigateTo,
    navigateBack,
    EventChannel,
    route,
  } = useTzRouter();
  return () => {
    const { status } = state.consistBean;
    const { consistId } = state;

    watch(
      () => state.showLoading,
      (newVal) => {
        if (newVal) {
          // state.handleBtnDisabled = true;
          Taro.showLoading({
            title: "加载中",
          });
        } else {
          // state.handleBtnDisabled = false;
          Taro.hideLoading();
        }
      }
    );

    // 重新编辑
    const editClick = () => {
      navigateTo({
        path: "/pages/subCN/truck/home/index",
        query: {
          opt: 1,
          type: state.inOutTypeDiffType,
          consistId,
          detailToEdit: 1,
        },
      });
    };

    // 解除捆绑
    const unBindClick = () => {
      Taro.showModal({
        content: "确定解绑该条记录吗?",
        confirmText: "确定",
        cancelText: "取消",
      })
        .then((res) => {
          if (res.cancel) {
            return Promise.reject("cancel");
          } else {
            state.handleBtnDisabled = true;
            Taro.showLoading({
              title: "加载中",
            });
            return deleteCellConsistApi(consistId);
          }
        })
        .then(() => {
          Taro.hideLoading();
          // 发起订阅消息的授权
          Taro.requestSubscribeMessage({
            tmplIds: templateIdList,
          });

          return Taro.showModal({
            content:
              "提示:已申报到海关,请等待3~5分钟后,进入【确报查询】查看状态.",
            confirmText: "好",
            showCancel: false,
          });
        })
        .then(() => {
          navigateBack({
            delta: 1,
            event: {
              type: "backRefresh",
            },
          });
        })
        .catch((err) => {
          Taro.hideLoading();
          state.handleBtnDisabled = false;
          if (err === "cancel") return;
          Taro.showToast({
            title: err.data.msg || "解绑失败",
            icon: "none",
            duration: 3000,
          });
        });
    };

    const sendApplyBind = () => {
      if (
        userType.isPersonal &&
        (state.totalMoney <= 0 || state.totalMoney < state.price)
      ) {
        Taro.showModal({
          content: "账户余额不足,立即充值!",
          confirmText: "确定",
          cancelText: "取消",
        }).then((res) => {
          if (res.cancel) return;
          redirectTo({
            path: "/pages/subUser/recharge/index",
          });
        });
        return;
      }
      state.showLoading = true;
      callConsistApi(consistId)
        .then(() => {
          Taro.hideLoading();
          // 发起订阅消息的授权
          Taro.requestSubscribeMessage({
            tmplIds: templateIdList,
          });

          return Taro.showModal({
            content:
              "提示:已申报到海关,请等待30秒~2分钟后,进入【确报查询】查看状态.",
            confirmText: "好",
            showCancel: false,
          });
        })
        .then(() => {
          // 新增数据-重定向到确报列表页
          state.isNewOrder
            ? redirectTo({
                path: "/pages/subCN/confirm/home/index",
              })
            : navigateBack({
                delta: 1,
                event: {
                  type: "backRefresh",
                },
              });
        })
        .catch((err) => {
          $TzNotify.danger(err.data.msg || "申请捆绑失败");
          state.showLoading = false;
          state.handleBtnDisabled = false;
        });
    };

    // 申请捆绑
    const applyBindClick = () => {
      if (state.handleBtnDisabled) return;
      state.showLoading = true;
      state.handleBtnDisabled = true;
      checkItemBundleApi(consistId)
        .then((res) => {
          state.showLoading = false;
          const { errMsgArr, warnMsgArr } = res.data;
          if (errMsgArr && errMsgArr.length) {
            $TzNotify.danger({ message: errMsgArr.toString(), duration: 4000 });
            return Promise.reject();
          } else if (warnMsgArr && warnMsgArr.length) {
            const warnMsg = warnMsgArr
              .map((item, index) => `${index + 1}.${item}\n`)
              .join("");
            return Taro.showModal({
              content: warnMsg + "是否继续？",
              confirmText: "是",
              cancelText: "否",
            });
          }
        })
        .then((res) => {
          if (res && res.cancel) {
            state.handleBtnDisabled = false;
            return;
          }
          sendApplyBind();
        })
        .catch(() => {
          state.showLoading = false;
          state.handleBtnDisabled = false;
        });
    };

    let btnDom;
    if (["00", "03"].indexOf(status) !== -1) {
      // 00 草稿  03 重新编辑
      btnDom = (
        <tz-view class="btn-wrap abreast">
          <tz-button
            disabled={state.handleBtnDisabled}
            type="default"
            onClick={editClick}
          >
            重新编辑
          </tz-button>
          <tz-button
            disabled={state.handleBtnDisabled}
            type="danger"
            onClick={applyBindClick}
          >
            申请捆绑
          </tz-button>
        </tz-view>
      );
    } else if (status === "60") {
      // 60 退单重报
      btnDom = (
        <tz-button
          disabled={state.handleBtnDisabled}
          type="danger"
          onClick={applyBindClick}
        >
          申请捆绑
        </tz-button>
      );
    } else if (["31", "52"].indexOf(status) !== -1) {
      // 31 捆绑成功  52 解绑失败
      btnDom = (
        <tz-button
          disabled={state.handleBtnDisabled}
          type="danger"
          onClick={unBindClick}
        >
          解除捆绑
        </tz-button>
      );
    } else if (["32", "51"].indexOf(status) !== -1) {
      // 32 捆绑失败  51 解绑成功
      btnDom = (
        <tz-button
          disabled={state.handleBtnDisabled}
          type="default"
          onClick={editClick}
        >
          重新编辑
        </tz-button>
      );
    }

    return (
      <tz-view class="btn-area">
        {btnDom}
        <tz-button
          disabled={state.handleBtnDisabled}
          type="primary"
          onClick={() => {
            state.isNewOrder
              ? redirectTo({
                  path: "/pages/subCN/confirm/home/index",
                })
              : navigateBack({ delta: 1 });
          }}
        >
          返回查询
        </tz-button>
      </tz-view>
    );
  };
};
